<template>
  <div class="rooms-container">
    <div class="search-bar">
      <el-form :inline="true" :model="roomForm">
        <el-form-item label="会议室名称">
          <el-input v-model="roomForm.name" placeholder="可输入会议室名称"></el-input>
        </el-form-item>
        <el-form-item label="会议室类型">
          <el-select v-model="roomForm.type" placeholder="全部类型" clearable style="width: 120px;">
            <el-option label="教室型" :value="0"></el-option>
            <el-option label="圆桌型" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="roomForm.status" placeholder="全部状态" clearable style="width: 120px;">
            <el-option label="空闲" :value="0"></el-option>
            <el-option label="锁定" :value="1"></el-option>
            <el-option label="预定" :value="2"></el-option>
            <el-option label="使用" :value="3"></el-option>
            <el-option label="维护" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="容纳人数">
          <el-input-number v-model="roomForm.minSeats" :min="0" placeholder="可筛选最小容纳人数" @change="handleMinSeatsChange" style="width: 220px;"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">刷新</el-button>
          <el-button type="success" @click="handleAdd">新增会议室</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="roomList" border style="width: 100%">
      <el-table-column prop="name" label="会议室名称" width="220">
        <template #default="scope">
          {{ scope.row.name }}
          <el-tag size="small" :type="getStatusTagType(scope.row.curStatus)" style="margin-left: 5px;">
            {{ getStatusText(scope.row.curStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" width="80">
        <template #default="scope">
          {{ scope.row.type === 0 ? '教室型' : scope.row.type === 1 ? '圆桌型' : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="area" label="面积(平方米)" width="120"></el-table-column>
      <el-table-column prop="seatNum" label="座位数" width="80"></el-table-column>
      <el-table-column prop="price" label="价格(元/小时)" width="120"></el-table-column>
      <el-table-column label="设备" width="120" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleViewCurDevices(scope.row)">查看设备</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleViewStatus(scope.row)">查看状态</el-button>
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>

    <!-- 会议室信息编辑表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="50%"
      :before-close="handleDialogClose"
    >
      <el-form :model="roomForm" :rules="rules" ref="roomFormRef" label-width="100px">
        <el-form-item label="会议室名称" prop="name">
          <el-input v-model="roomForm.name"></el-input>
        </el-form-item>
        <el-form-item label="会议室类型" prop="type">
          <el-select v-model="roomForm.type" placeholder="请选择会议室类型">
            <el-option label="教室型" :value="0"></el-option>
            <el-option label="圆桌型" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会议室面积" prop="area">
          <el-input-number v-model="roomForm.area" :min="0" :precision="2"></el-input-number>
        </el-form-item>
        <el-form-item label="座位数" prop="seatNum">
          <el-input-number v-model="roomForm.seatNum" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="价格(每小时)" prop="price">
          <el-input-number v-model="roomForm.price" :min="0" :precision="2"></el-input-number>
        </el-form-item>
        <el-form-item label="设备" prop="deviceList">
          <el-select v-model="roomForm.deviceList" multiple placeholder="请选择设备">
            <el-option
              v-for="device in deviceList"
              :key="device.id"
              :label="device.name"
              :value="device.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设备列表对话框 -->
    <el-dialog
      title="设备列表"
      v-model="deviceDialogVisible"
      width="30%"
    >
      <el-table :data="currentRoomDevices" border style="width: 100%">
        <el-table-column prop="name" label="设备名称"></el-table-column>
        <el-table-column prop="description" label="设备描述"></el-table-column>
      </el-table>
    </el-dialog>

    <!-- 会议室详情对话框 -->
    <el-dialog 
      title="会议室详情" 
      v-model="roomDetailVisible" 
      width="42%" 
      @closed="roomStatusString = ''" 
      @close="selectedDate= ''"
    >
      <div class="room-detail">
        <div class="detail-item">
          <span class="label">查看会议室状态：</span>
          <el-date-picker
            v-model="selectedDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            :disabled-date="(time) => time.getTime() < Date.now() - 86400000"
            @change="fetchRoomStatus"
          />
        </div>
        <div class="detail-item" v-if="roomStatusString">
          <div class="time-status-grid" style="display: flex; flex-wrap: wrap;">
            <div v-for="(status, index) in roomStatusArray" :key="index" class="time-status-item" style="margin-right: 10px; margin-bottom: 1px;">
              <span class="time-label">{{ index.toString().padStart(2, '0') }}:00 - {{ (index + 1).toString().padStart(2, '0') }}:00</span>
              <el-tag :type="getStatusTagType(Number(status))" size="small" style="margin-left: 5px;">
                {{ getStatusText(Number(status)) }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import request from '../../api/request'
import dayjs from 'dayjs'


const roomList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const deviceList = ref([])
const roomStatusString = ref('')
const roomStatusArray = computed(() => roomStatusString.value.split(''))
const roomDetailVisible = ref(false)
const selectedDate = ref('')
const currentRoom = ref({})

const dialogVisible = ref(false)
const dialogTitle = ref('')
const roomFormRef = ref(null)
const deviceDialogVisible = ref(false)
const currentRoomDevices = ref([])
const roomForm = ref({
  id: null,
  name: null,
  type: null,
  area: null,
  seatNum: null,
  status: null,
  price: null,
  deviceList: [],
  minSeats: null,
  pageNum: 1,
  pageSize: 10
})

const rules = {
  name: [{ required: true, message: '请输入会议室名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择会议室类型', trigger: 'change' }],
  area: [{ required: true, message: '请输入会议室面积', trigger: 'blur' }],
  seatNum: [{ required: true, message: '请输入座位数', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  minSeats: [
    {
      validator: (rule, value, callback) => {
        if (value !== undefined && value !== null && !Number.isInteger(value)) {
          callback(new Error('只能输入整数'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
}

const getStatusText = (status) => {
  switch (status) {
    case 0: return '空闲';
    case 1: return '锁定';
    case 2: return '预定';
    case 3: return '使用';
    case 4: return '维护';
    default: return '';
  }
};

const getStatusTagType = (status) => {
  switch (status) {
    case 0: return 'success'; // 空闲
    case 1: return 'warning'; // 锁定
    case 2: return 'primary'; // 预定
    case 3: return 'danger';  // 使用
    case 4: return 'info';    // 维护
    default: return '';
  }
};

const fetchRoomStatus = async () => {
  if (!selectedDate.value || !currentRoom.value.id){
    roomStatusString.value = ''
    return
  }
  roomStatusString.value = currentRoom.value.status
}

const getRoomList = async () => {
  try {
    const response = await request({
      url: '/common/meeting-room',
      method: 'post',
      data: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        date: dayjs(new Date()).format('YYYY-MM-DD HH-mm-ss'),
        ...roomForm.value
      }
    }
    )
    if (response.success) {
      roomList.value = response.data.records.map(room => {
        const currentHourStatus = getCurrentHourStatus(room.status)
        return {
          ...room,
          curStatus: parseInt(currentHourStatus)
        }
      })
      total.value = response.data.total
    }
  } catch (error) {
    ElMessage.error('获取会议室列表失败:',error.message)
  }
}

const getCurrentHourStatus = (status) => {
  const currentHour = new Date().getHours(); // 获取当前小时，范围 0~23
  return status.charAt(currentHour);         // 取出对应的字符
}

const getDeviceList = async () => {
  try {
    const response = await request.post('/admin/media-device-list', {
      pageNum: 1,
      pageSize: 10000
    })
    if (response.code === 200) {
      deviceList.value = response.data.records.map(device => ({
        id: device.id,
        name: device.name
      }))
    }
  } catch (error) {
    console.error('获取设备列表失败：', error)
    ElMessage.error('获取设备列表失败:',error.message)
  }
}

const handleViewStatus = (room) => {
  currentRoom.value = room
  roomDetailVisible.value = true
}

const handleViewCurDevices = async (room) => {
  try {
    const response = await request({
      url:'/common/media', 
      method: 'get',
      params:{
        meetingRoomId: room.id
      }
    })
    currentRoomDevices.value = response.data
    deviceDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取会议室设备列表失败：' + error.message)
  }
}

const submitAddRoom = async () => {
  try {
    const payload = {
      name: roomForm.value.name,
      type: Number(roomForm.value.type),
      area: Number(roomForm.value.area),
      seatNum: Number(roomForm.value.seatNum),
      price: Number(roomForm.value.price),
      status: Number(roomForm.value.status),
      deviceList: roomForm.value.deviceList.map(id => Number(id)),
    };
    await request({
      url: '/admin/add-meeting-room',
      method: 'post',
      data: payload
    });
    ElMessage.success(`${roomForm.value.name} 会议室新增成功`);
    dialogVisible.value = false;
    resetSearch();
    getRoomList();
  } catch (error) {
    ElMessage.error(`新增失败: ${error.message}`);
  }
};

const submitUpdateRoom = async () => {
  try {
    const payload = {
      id: roomForm.value.id,
      name: roomForm.value.name,
      type: Number(roomForm.value.type),
      area: Number(roomForm.value.area),
      seatNum: Number(roomForm.value.seatNum),
      price: Number(roomForm.value.price),
      status: Number(roomForm.value.status),
      deviceList: roomForm.value.deviceList.map(id => Number(id)),
    };
    await request({
      url: '/admin/modify-meeting-room',
      method: 'put',
      data: payload
    });
    ElMessage.success(`${roomForm.value.name} 修改成功`);
    dialogVisible.value = false;
    resetSearch();
    getRoomList();
  } catch (error) {
    console.error('修改会议室失败：', error);
    ElMessage.error(`修改失败: ${error.message}`);
  }
};

const submitForm = async () => {
  if (!roomFormRef.value) return;

  await roomFormRef.value.validate(async (valid) => {
    if (valid) {
      if (roomForm.value.id) {
        await submitUpdateRoom();
      } else {
        await submitAddRoom();
      }
    }
  });
};

const handleAdd = () => {
  dialogTitle.value = '新增会议室'
  roomForm.value = {
    id: '',
    name: '',
    type: 0,
    area: 0,
    seatNum: 0,
    price: 0,
    deviceList: []
  }
  dialogVisible.value = true
}

const handleEdit = async (row) => {
  dialogTitle.value = '编辑会议室';
  try {
    const response = await request({
      url:'/common/media', 
      method: 'get',
      params:{
        meetingRoomId: row.id
      }
    });
    const currentDevices = response.data;
    const deviceIds = currentDevices.map(device => device.id);
    roomForm.value = { 
      ...row, 
      deviceList: deviceIds 
    };
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取会议室设备列表失败：' + error.message);
  }
};

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该会议室吗?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await request({
      url: `/admin/delete-meeting-room`,
      method: 'delete',
      data: {
        id: row.id
      }
    })
    ElMessage.success('删除成功')
    resetSearch()
    getRoomList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除会议室失败：', error)
      ElMessage.error('删除失败:',error.message)
    }
  }
}

const handleSearch = () => {
  currentPage.value = 1
  getRoomList()
}

const resetSearch = () => {
  roomForm.value = {
    id: null,
    name: null,
    type: null,
    area: null,
    seatNum: null,
    status: null,
    price: null,
    deviceList: [],
    minSeats: null,
    pageNum: currentPage,
    pageSize: pageSize
  }
  handleSearch()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getRoomList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getRoomList()
}

const handleDialogClose = (done) => {
  roomFormRef.value?.resetFields()
  done()
}

onMounted(() => {
  getRoomList()
  getDeviceList()
})

const handleMinSeatsChange = (value) => {
  if (value !== undefined && value !== null && !Number.isInteger(value)) {
    ElMessage.error('只能输入整数');
    roomForm.value.minSeats = value ? Math.floor(value) : 0;
  }
}
</script>

<style scoped>
.rooms-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.device-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.room-detail {
  padding: 0 20px;
}

.detail-item {
  margin-bottom: 16px;
  display: flex;
  align-items: flex-start;
}


.detail-item .label {
  color: #666;
  margin-right: 50px;
  width: 100px;
  color: #606266;
  flex: 0 0 120px; 
}

.time-status-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  margin-top: 10px;
}

.time-status-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.time-label {
  font-size: 12px;
  color: #666;
}

.detail-actions {
  margin-top: 24px;
  display: flex;
  gap: 12px;
  justify-content: center;
}
</style>